<template>
  <Card
    title="收件箱"
    :bordered="false"
    :head-style="{ padding: '0' }"
    :body-style="{ padding: '10px 0' }"
    v-loading="loading"
  >
    <template #extra>
      <div class="flex gap-2 items-center" v-if="message_oaGetAgentInfo.isDeptMgr">
        <template v-if="emailType == 2">
          <div>代理部门：{{ message_oaGetAgentInfo?.agentDeptName || '无' }}</div>
          <Button type="primary" @click="handleSetProxy(1)"> 设置代理 </Button>
          <Button
            type="primary"
            @click="handleSetProxy(2)"
            v-if="message_oaGetAgentInfo?.agentDeptName"
          >
            取消代理
          </Button>
        </template>
        <Button type="primary" @click="handleChangeEmail" v-if="userInfo?.deptCode">
          切换邮箱
        </Button>
      </div>
    </template>
    <div style="background-color: #e7eff6" class="flex justify-start gap-2 p-8px">
      <Button type="primary" @click="handleRefresh">
        <template #icon>
          <RedoOutlined />
        </template>
        刷新
      </Button>
      <Button @click="handleDeleteBatch">
        <template #icon> <DeleteOutlined style="color: red" /> </template>
        删除
      </Button>
      <Button type="primary" @click="handleTransmit">
        <template #icon>
          <SendOutlined />
        </template>
        转发
      </Button>
      <Button type="primary" @click="handleRead">
        <template #icon>
          <ReadOutlined />
        </template>
        置为已读
      </Button>
    </div>
    <BasicTable @register="registerTable" class="custom-table">
      <!-- <template #toolbar> </template> -->
      <template #form-kind="{ model, field }">
        <Input v-model:value="model['what']" placeholder="请输入" allowClear>
          <template #addonBefore>
            按
            <Select
              :options="byOptions"
              v-model:value="model[field]"
              style="width: 100px; margin-left: 5px"
              placeholder="请选择"
              allowClear
            />
          </template>
        </Input>
      </template>
      <template #title="{ text, record }">
        <a-button
          type="link"
          @click="handleView(record)"
          :style="{ fontWeight: record.readed ? '' : 'bold' }"
        >
          {{ text }}
        </a-button>
      </template>
      <!-- <template #senderRealName="{ text, record }">
        <a-button type="link" @click="handleUserDetails(record)">
          {{ text }}
        </a-button>
      </template> -->
      <template #action="{ record }">
        <TableAction
          :actions="[
            {
              icon: 'clarity:info-standard-line',
              onClick: handleView.bind(null, record),
              tooltip: '查看',
            },
            {
              icon: 'ant-design:delete-outlined',
              color: 'error',
              popConfirm: {
                title: '是否确认删除',
                placement: 'leftBottom',
                confirm: handleDelete.bind(null, record),
              },
            },
          ]"
        />
      </template>
    </BasicTable>
    <SelectDeptModal
      @register="registerModalSelectDeptModal"
      @success="handleCallBackSelectDeptModal"
    />
  </Card>
</template>
<script lang="ts">
  import { defineComponent, h, ref, onMounted, inject, computed } from 'vue';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import { columns, searchFormSchema, byOptions } from './inbox.data';
  import {
    getMessage_oaListInbox,
    getMessage_oaSetReaded,
    getMessage_oaDelToDustbin,
    getMessage_oaDel,
    getMessage_oaGetAgentInfo,
    getMessage_oaCancelAgent,
  } from '/@/api/email/email';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useGo } from '/@/hooks/web/usePage';
  import { useModal } from '/@/components/Modal';
  import { Card, Input, Select, Button } from 'ant-design-vue';
  import { RedoOutlined, DeleteOutlined, SendOutlined, ReadOutlined } from '@ant-design/icons-vue';
  import { useUserStore } from '/@/store/modules/user';
  import SelectDeptModal from '../common/SelectDeptModal.vue';

  export default defineComponent({
    name: 'InboxList',
    components: {
      BasicTable,
      TableAction,
      Card,
      Input,
      Select,
      Button,
      RedoOutlined,
      DeleteOutlined,
      SendOutlined,
      ReadOutlined,
      SelectDeptModal,
    },
    emits: ['handle-transmit', 'handle-view'],
    setup(_, { emit }) {
      const go = useGo();
      const loading = ref(false);
      const { createMessage, createConfirm } = useMessage();
      const userStore = useUserStore();
      const userInfo = userStore.getUserInfo || {};
      const internalEmail = inject('internalEmail') as any;
      const emailType = computed(() => internalEmail.emailType.value);
      const [registerTable, { reload, getSelectRowKeys, getSelectRows }] = useTable({
        title: '',
        api: getMessage_oaListInbox,
        columns,
        formConfig: {
          labelWidth: 0,
          schemas: searchFormSchema,
          autoSubmitOnEnter: true,
          actionColOptions: {
            sm: 8,
            md: 8,
            lg: 6,
            xl: 5,
            xxl: 3,
          },
        },
        searchInfo: {
          action: 'search',
        }, //额外的参数
        beforeFetch: (info) => {
          if (internalEmail.emailType.value == 2) {
            info.isDept = true;
          }
          return info;
        },
        rowSelection: {
          type: 'checkbox',
          columnWidth: 40,
        },
        clickToRowSelect: false,
        useSearchForm: true,
        showTableSetting: false,
        bordered: true,
        indexColumnProps: { width: 50 },
        showIndexColumn: true,
        rowKey: 'id',
        canResize: false,
        actionColumn: {
          width: 120,
          title: '操作',
          dataIndex: 'action',
          slots: { customRender: 'action' },
          fixed: undefined,
        },
      });

      async function handleDelete(record: Recordable) {
        try {
          loading.value = true;
          await getMessage_oaDelToDustbin({ ids: record.id });
          handleSuccess();
        } catch (error) {
          console.log(error);
        } finally {
          loading.value = false;
        }
      }

      async function handleDeleteBatch() {
        let checkes = getSelectRowKeys();
        if (checkes.length == 0) {
          createMessage.warn('删除数据不能为空');
          return;
        }

        createConfirm({
          iconType: 'warning',
          title: () => h('span', '您确定删除么？'),
          onOk: async () => {
            let ids = checkes.join(',');
            try {
              loading.value = true;
              await getMessage_oaDelToDustbin({ ids: ids });
              handleSuccess();
            } catch (error) {
              console.log(error);
            } finally {
              loading.value = false;
            }
          },
        });
      }

      function handleSuccess() {
        reload();
      }

      function handleView(record: Recordable) {
        emit('handle-view', record);
      }

      //用户信息
      // const handleUserDetails = (record: Recordable) => {
      //   go({
      //     path: '/userDetail',
      //     query: {
      //       userId: record.sendId,
      //     },
      //   });
      // };

      //刷新
      const handleRefresh = () => {
        reload();
      };

      //转发
      const handleTransmit = () => {
        const rews = getSelectRows();
        if (rews.length == 0) {
          createMessage.warn('请选择数据');
          return;
        }
        emit('handle-transmit', rews[0]);
      };

      //置为已读
      const handleRead = async () => {
        let checkes = getSelectRowKeys();
        if (checkes.length == 0) {
          createMessage.warn('请选择数据');
          return;
        }
        const moduleCodes = checkes.join(',');
        try {
          loading.value = true;
          await getMessage_oaSetReaded({ ids: moduleCodes, isReaded: true });
          createMessage.success('操作成功');
          handleRefresh();
        } finally {
          loading.value = false;
        }
      };

      const message_oaGetAgentInfo = ref<Recordable>({});
      //获取邮箱代理的部门
      const getMessage_oaGetAgentInfoData = async () => {
        console.log('userInfo', userInfo);
        const deptCode = userInfo.deptCode;
        if (!deptCode) {
          return;
        }
        try {
          const res = await getMessage_oaGetAgentInfo({ deptCode: deptCode });
          if (res) {
            message_oaGetAgentInfo.value = res;
          } else {
            message_oaGetAgentInfo.value = {};
          }
        } finally {
        }
      };

      const [registerModalSelectDeptModal, { openModal }] = useModal();
      const handleSetProxy = (type) => {
        if (type == 1) {
          openModal(true, {
            isUpdate: false,
            record: {
              deptCode: userInfo.deptCode,
            },
          });
        } else if (type == 2) {
          createConfirm({
            iconType: 'warning',
            title: () => h('span', '您确定取消代理么？'),
            onOk: async () => {
              try {
                loading.value = true;
                const deptCode = userInfo.deptCode;
                await getMessage_oaCancelAgent({ deptCode: deptCode });
                getMessage_oaGetAgentInfoData();
              } catch (error) {
                console.log(error);
              } finally {
                loading.value = false;
              }
            },
          });
        }
      };
      const handleCallBackSelectDeptModal = () => {
        getMessage_oaGetAgentInfoData();
      };
      const handleChangeEmail = () => {
        internalEmail.handleChangeEmail();
      };

      onMounted(() => {
        getMessage_oaGetAgentInfoData();
      });
      return {
        registerTable,
        handleDelete,
        handleSuccess,
        handleDeleteBatch,
        handleView,
        handleRead,
        handleRefresh,
        handleTransmit,
        loading,
        byOptions,
        message_oaGetAgentInfo,
        handleSetProxy,
        handleChangeEmail,
        registerModalSelectDeptModal,
        handleCallBackSelectDeptModal,
        emailType,
        userInfo,
        // handleUserDetails,
      };
    },
  });
</script>

<style lang="less" scoped>
  :deep(.ant-card-head-title) {
    padding: 8px 8px 0;
  }
  .custom-table {
    padding: 0;
    :deep(.ant-table-wrapper) {
      padding: 0;
    }
  }
  :deep(.ant-form) {
    padding: 10px 0 5px;
    margin-bottom: 0;
  }
</style>
